﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;
using System.Text;
using System.Web.Services;

using CE.Database;
using CE.Mail;
using CE.Global;
using CE.CarInsurance;
using CE.User;
using CE.Security;

public partial class car_insurance_promo_email_confirm : System.Web.UI.Page
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (Session[General.CarId] == null)
        {
            Response.Redirect("promo-car-quote.aspx");
        }

        #region Promotion Status
        bool _IsPromo = false;
        string _Promo = CE.Global.General.GetUTCDateTime().ToString("yyyyMMdd");
        Int64 _intPromo = 0;
        if (!Int64.TryParse(_Promo, out _intPromo))
        {
            _intPromo = 0;
        }
        //if (Session["Language"] != null & Session["Language"].ToString() == "en-US")
        //{
        if ((_intPromo >= 20150413 && _intPromo <= 20150430) || (_intPromo >= 25580413 && _intPromo <= 25580430))
        {
            _IsPromo = true;
        }
        //}
        //else if (Session["Language"] != null & Session["Language"].ToString() == "th-TH")
        //{
        //    if (_intPromo >= 25580413 && _intPromo <= 25580430)
        //    {
        //        _IsPromo = true;
        //    }
        //}
        if (!_IsPromo)
        {
            Response.Redirect("car-quote.aspx");
        }
        #endregion

        if (!IsPostBack)
        {
            divCallMe.Visible = true;
            divEmailMessage.Visible = false;
            if (Request.QueryString["sent"] != null && Request.QueryString["sent"].ToString() != string.Empty && Request.QueryString["sent"].ToString() == "1")
            {
                divEmailMessage.Visible = true;
                divCallMe.Visible = false;
            }
            LoadTitles();
            txtUserName.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtUserName.ClientID + "','" + rfvUserName.ClientID + "','" + revUserName.ClientID + "');DefaultName(this, event);");
            txtUserName.Attributes.Add("onfocus", "ClearText(this, event);");
            txtUserEmail.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtUserEmail.ClientID + "','" + rfvUserEmail.ClientID + "','" + revUserEmail.ClientID + "');DefaultEmail(this, event);");
            txtUserEmail.Attributes.Add("onfocus", "ClearText(this, event);");
            txtUserMobile.Attributes.Add("onblur", "RemoveSpace(this);ShowValidationEffectTwo('" + txtUserMobile.ClientID + "','" + rfvUserMobile.ClientID + "','" + revUserMobile.ClientID + "');DefaultPhone(this, event);");
            txtUserMobile.Attributes.Add("onfocus", "ClearText(this, event);");

            HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
            if (_cookie != null)
            {
                txtUserEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                txtUserName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtUserMobile.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                string _isaccept = "FALSE";
                string[] _CK = _cookie.Value.Split('&');
                if (_CK.Length > 3)
                {
                    _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                    if (_isaccept != null && _isaccept == "TRUE")
                    {
                        hdnIsAceept.Value = "TRUE";
                    }
                }
            }
            divAgreement.Style.Add("display", "");
            if (hdnIsAceept.Value == "TRUE")
            {
                txtIsAccept.Text = "1";
                chkAggrement.Checked = true;
                divAgreement.Style.Add("display", "none");
            }
            //if (!IsPostBack)
            //{
            lblMessage1.Text = Resources.CarMenu.EmailQuoteMessage;
            lblMessage2.Text = Resources.CarMenu.HotLineMessage;
            if (Request.QueryString["email"] != null && Request.QueryString["email"].ToString() != string.Empty)
            {
                if (Request.QueryString["email"].ToString() == "1")
                {
                    lblMessage1.Text = Resources.CarMenu.AppMessage;
                }
            }
            //}
            if (Request.QueryString["qid"] != null && Request.QueryString["qid"].ToString() != string.Empty)
            {
                hdnQuoteId.Value = Request.QueryString["qid"].ToString();
            }
            if (Request.QueryString["cid"] != null && Request.QueryString["cid"].ToString() != string.Empty)
            {
                hdnCarId.Value = Request.QueryString["cid"].ToString();
            }
            if (Request.QueryString["pid"] != null && Request.QueryString["pid"].ToString() != string.Empty)
            {
                hdnPolicyId.Value = Request.QueryString["pid"].ToString();
            }
            hdnRedirect.Value = "promo-results.aspx?type=email&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value;
        }
    }

    protected void btnBack_Click(object sender, EventArgs e)
    {
        Response.Redirect("promo-results.aspx?type=email&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            ChangeValidationEffectServerSide("email");
            Page.Validate("email");
            if (Page.IsValid)
            {
                Int64 _userId = 0;
                Int64 _carId = 0;
                Int64 _carResultId = 0;
                Int64 _ProviderId = 0;
                Int64 _ExistingUserId = 0;
                string ExistingEmail = "";
                if (Session[General.UserEmail] != null && Session[General.UserEmail].ToString() != string.Empty)
                {
                    ExistingEmail = Session[General.UserEmail].ToString();
                }
                if (Session[CE.Global.General.UserId] != null)
                {
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out _ExistingUserId))
                    {
                        _ExistingUserId = 0;
                    }
                }
                if (Session[General.CarId] != null)
                {
                    if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                    {
                        _carId = 0;
                    }
                }

                #region Customer Details
                Account _useraccount = new Account();
                AccountDB _useraccountdb = new AccountDB();

                _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim().ToLower(), 400);
                if (_useraccount != null && _useraccount.CEID > 0)
                {
                    _userId = _useraccount.CEID;
                    Profile _userprofile = new Profile();
                    ProfileDB _userprofiledb = new ProfileDB();

                    Contact _usercontact = new Contact();
                    ContactDB _usercontactdb = new ContactDB();

                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);

                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        _userprofile.SurName = string.Empty;
                        _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                        _userprofile.IsAcceptTC = true;
                        _userprofiledb.Insert(_userprofile);
                    }
                    _usercontact = _usercontactdb.GetContact(_useraccount.CEID);
                    if (_usercontact != null && _usercontact.ContactId > 0)
                    {
                        _usercontact.Mobile = txtUserMobile.Text.Trim();
                        _usercontactdb.Insert(_usercontact);
                    }
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserName] = _userprofile.FirstName;
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_userprofile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    Session[CE.Global.General.UserPhoneNo] = _usercontact.Mobile;
                    _useraccount = null;
                    _useraccountdb = null;
                    _userprofile = null;
                    _userprofiledb = null;
                    _usercontact = null;
                    _usercontactdb = null;
                    if (_ExistingUserId != _userId)
                    {
                        UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                    }
                }
                else
                {
                    //General.ClearAllSession(this.Page, "USER");
                    UpdateProfile(_userId, _carId);
                    if (Session[CE.Global.General.UserId] != null)
                    {
                        if (!Int64.TryParse(Session[CE.Global.General.UserId].ToString(), out _userId))
                        {
                            _userId = 0;
                        }
                    }
                    UpdateUserIdCarDetails(_carId, _userId, _ExistingUserId, ExistingEmail, "SWITCH", txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                    SendMailToUser(txtUserEmail.Text.Trim().ToLower(), Session[General.UserName].ToString(), txtUserMobile.Text.Trim());
                }
                if (chkAggrement.Checked)
                {
                    hdnIsAceept.Value = "TRUE";
                }
                SetCookies();
                HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
                #endregion

                if (Session[General.UserId] != null)
                {
                    if (!Int64.TryParse(Session[General.UserId].ToString(), out _userId))
                    {
                        _userId = 0;
                    }
                }
                if (Session[General.CarId] != null)
                {
                    if (!Int64.TryParse(Session[General.CarId].ToString(), out _carId))
                    {
                        _carId = 0;
                    }
                }

                if (Request.QueryString["prid"] != null && Request.QueryString["prid"].ToString() != string.Empty)
                {
                    if (!Int64.TryParse(Request.QueryString["prid"].ToString(), out _ProviderId))
                    {
                        _ProviderId = 0;
                    }
                }

                if (Request.QueryString["rid"] != null && Request.QueryString["rid"].ToString() != string.Empty)
                {
                    if (!Int64.TryParse(Request.QueryString["rid"].ToString(), out _carResultId))
                    {
                        _carResultId = 0;
                    }
                }
                if (_userId > 0 && _carId > 0)
                {
                    PromotionIdUpdate(_userId, _carId);
                }

                if (_userId > 0 && _carId > 0 && _ProviderId > 0)
                {
                    EmailQuote(_carResultId.ToString());
                    //Response.Redirect("promo-email-confirm.aspx?rid=" + _carResultId.ToString() + "&prid=" + _ProviderId.ToString() + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value + "&sent=1");
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void LoadTitles()
    {
        lblApplicationTitle.Text = Resources.CarMenu.Sendusemail;
        lblThanksTitle.Text = Resources.CarMenu.ThankYou;
        lblMessage1.Text = Resources.CarMenu.EmailQuoteMessage;
        lblMessage2.Text = Resources.CarMenu.HotLineMessage;
        btnSubmit.Text = Resources.ProposalForm.Submit;
        lblAggrement.Text = Resources.UserMessage.Aggrement;
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtUserName.Text = HttpUtility.HtmlEncode(txtUserName.Text.Trim());
        txtUserEmail.Text = HttpUtility.HtmlEncode(txtUserEmail.Text);
        txtUserMobile.Text = HttpUtility.HtmlEncode(txtUserMobile.Text);
        
        #region user
        //Name
        if (rfvUserName.Enabled && rfvUserName.ValidationGroup == strValidationGroup)
        {
            rfvUserName.Validate();
            if (rfvUserName.IsValid == false)
            {
                txtUserName.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtUserName.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "text-fields";
        }

        if (revUserName.Enabled && revUserName.ValidationGroup == strValidationGroup)
        {
            if (rfvUserName.IsValid)
            {
                revUserName.Validate();
                if (revUserName.IsValid == false)
                {
                    txtUserName.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtUserName.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtUserName.ControlStyle.CssClass = "text-fields";
        }

        //Email
        if (rfvUserEmail.Enabled && rfvUserEmail.ValidationGroup == strValidationGroup)
        {
            rfvUserEmail.Validate();
            if (rfvUserEmail.IsValid == false)
            {
                txtUserEmail.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtUserEmail.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "text-fields";
        }

        if (revUserEmail.Enabled && revUserEmail.ValidationGroup == strValidationGroup)
        {
            if (rfvUserEmail.IsValid)
            {
                revUserEmail.Validate();
                if (revUserEmail.IsValid == false)
                {
                    txtUserEmail.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtUserEmail.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtUserEmail.ControlStyle.CssClass = "text-fields";
        }

        //Mobile No
        if (rfvUserMobile.Enabled && rfvUserMobile.ValidationGroup == strValidationGroup)
        {
            rfvUserMobile.Validate();
            if (rfvUserMobile.IsValid == false)
            {
                txtUserMobile.ControlStyle.CssClass = "text-fields validationError";
            }
            else
            {
                txtUserMobile.ControlStyle.CssClass = "text-fields";
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "text-fields";
        }

        if (revUserMobile.Enabled && revUserMobile.ValidationGroup == strValidationGroup)
        {
            if (rfvUserMobile.IsValid)
            {
                revUserMobile.Validate();
                if (revUserMobile.IsValid == false)
                {
                    txtUserMobile.ControlStyle.CssClass = "text-fields validationError";
                }
                else
                {
                    txtUserMobile.ControlStyle.CssClass = "text-fields";
                }
            }
        }
        else
        {
            txtUserMobile.ControlStyle.CssClass = "text-fields";
        }
        #endregion
    }

    private void GetUserDetails(string CustomerEmail)
    {
        try
        {
            AccountDB _accountdb = new AccountDB();
            Account _account = _accountdb.GetUserAccount(CustomerEmail.ToLower(), 400);
            if (_account != null)
            {
                Session[CE.Global.General.UserId] = _account.CEID;
                Session[CE.Global.General.UserTypeId] = _account.UserTypeId;
                Session[CE.Global.General.UserEmail] = _account.Email;

                Profile _profile = new Profile();
                ProfileDB _profiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                _contact = _contactdb.GetContact(_account.CEID);
                _profile = _profiledb.GetProfile(_account.CEID);

                if (_contact != null)
                {
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                }
                else
                {
                    Session[CE.Global.General.UserPhoneNo] = null;
                }
                if (_profile != null)
                {
                    if (_profile.FirstName != null && _profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.FirstName) + " " + Server.HtmlDecode(_profile.SurName);
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = Server.HtmlDecode(_profile.SurName);
                    }
                    if (_profile.IsAcceptTC != null)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_profile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }
                }
            }
        }
        catch (Exception ex)
        {
        }
    }

    private string EmailAddress
    {
        get { return txtUserEmail.Text.Trim(); }
    }

    private string MobileNumber
    {
        get { return txtUserMobile.Text.Trim(); }
    }

    private string Name
    {
        get { return txtUserName.Text.Trim(); }
    }

    private void SetCookies()
    {
        try
        {
            string _isAccept = "FALSE";
            if (hdnIsAceept.Value == "TRUE")
            {
                _isAccept = "TRUE";
            }
            HttpCookie _cookie = new HttpCookie("GGMobileQuote");
            _cookie.Values.Add("CustomerName", MySecurity.Encrypt(txtUserName.Text, true));
            _cookie.Values.Add("CustomerEmail", MySecurity.Encrypt(txtUserEmail.Text, true));
            _cookie.Values.Add("CustomerMobile", MySecurity.Encrypt(txtUserMobile.Text, true));
            _cookie.Values.Add("IsAccept", MySecurity.Encrypt(_isAccept, true));
            _cookie.Expires = DateTime.Now.AddDays(90);
            Response.Cookies.Add(_cookie);
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    private void GetCookies()
    {
        try
        {
            HttpCookie _cookie = Request.Cookies.Get("GGMobileQuote");
            if (_cookie != null)
            {
                txtUserName.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerName"), true);
                txtUserEmail.Text = MySecurity.Decrypt(_cookie.Values.Get("CustomerEmail"), true);
                string _mobile = MySecurity.Decrypt(_cookie.Values.Get("CustomerMobile"), true);
                txtUserMobile.Text = _mobile;
                string _isaccept = "FALSE";
                string[] _CK = _cookie.Value.Split('&');
                if (_CK.Length > 3)
                {
                    _isaccept = MySecurity.Decrypt(_cookie.Values.Get("IsAccept"), true);
                    if (_isaccept != null && _isaccept == "TRUE")
                    {
                        hdnIsAceept.Value = "TRUE";
                    }
                }
            }
        }
        catch (Exception Ex)
        {
            Ex = null;
        }
    }

    #region Change Email - create new account

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;

        if (UserId != 0)
        {
            Profile _profile = new Profile();
            ProfileDB _profiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);
            _retValue = UserId;
            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = "";
                _profile.FirstName = HttpUtility.HtmlEncode(txtUserName.Text);
                _profile.SurName = "";
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _profile.DOB = dteDOB;
                }
                if (_profile.Gender.ToString().Trim() == "")
                {
                    _profile.Gender = 'M';
                }
                _profile.Status = "Complete";
                _profile.IsAcceptTC = true;// chkAggrement.Checked;

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtUserMobile.Text.Trim();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[CE.Global.General.IsAcceptTC] = "0";
                    if (_profile.IsAcceptTC == true)
                    {
                        Session[CE.Global.General.IsAcceptTC] = "1";
                    }
                    if (_contact != null)
                    {
                        Session[General.UserPhoneNo] = _contact.Mobile;
                    }
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }       
        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            Profile _userprofile = new Profile();
            ProfileDB _userprofiledb = new ProfileDB();

            Contact _contact = new Contact();
            ContactDB _contactdb = new ContactDB();

            _useraccount = _useraccountdb.GetUserAccount(txtUserEmail.Text.Trim(), 400);
            if (_useraccount != null)
            {
                if (_useraccount.CEID > 0)
                {
                    _retVal = _useraccount.CEID;
                    _contact = _contactdb.GetContact(_useraccount.CEID);
                    Session[CE.Global.General.UserId] = _useraccount.CEID;
                    Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                    Session[CE.Global.General.UserEmail] = _useraccount.Email;
                    Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                    Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                    _userprofile = _userprofiledb.GetProfile(_useraccount.CEID);
                    if (_userprofile != null && _userprofile.ProfileId > 0)
                    {
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                    }
                }
            }
            else
            {

                long _result = -1;
                _useraccount = new Account();
                _useraccount.Email = txtUserEmail.Text.Trim().ToLower();
                string _authcode = txtUserMobile.Text.Trim();
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDMOBILECI";
                _useraccount.UserTypeId = 400;
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;
                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;
                if (_result > 0)
                {
                    _userprofile.Salutation = "";
                    _userprofile.FirstName = Server.HtmlEncode(txtUserName.Text);
                    _userprofile.SurName = "";
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _userprofile.DOB = dteDOB;
                    _userprofile.Gender = 'M';

                    _userprofile.Occupation = 140;
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = true;// chkAggrement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);

                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtUserMobile.Text.Trim();

                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                        Session[CE.Global.General.IsAcceptTC] = "0";
                        if (_userprofile.IsAcceptTC == true)
                        {
                            Session[CE.Global.General.IsAcceptTC] = "1";
                        }
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    private void UpdateUserIdCarDetails(Int64 CarId, Int64 UserId, Int64 ExistingUserId, string ExistingEmail, string ChangeStatus, string Email, string Name, string Mobile)
    {
        try
        {
            Int64 _result = -1;
            MyDatabase _db = new MyDatabase();
            DataTable _dtResult = new DataTable();
            string _spName = "sprocCarDetailUpdateSingleItemByUserId";
            SortedList _sPara = new SortedList();
            _sPara.Add("@CarId", CarId);
            _sPara.Add("@RefCEUserId", UserId);
            _sPara.Add("@ExistingUserId", ExistingUserId);
            _sPara.Add("@ExistingEmail", ExistingEmail);
            _sPara.Add("@ChangeStatus", ChangeStatus);
            _sPara.Add("@Email", Email);
            _sPara.Add("@Name", Name);
            _sPara.Add("@Mobile", Mobile);

            _result = _db.ExecuteNonSqlSP(_spName, _sPara);
        }
        catch (Exception ex)
        {
        }
    }

    #endregion

    private void EmailQuote(string carresultid)
    {
        string qs_carselected = carresultid;
        string _makemodel = "";
        string _garagetype = "";
        string _caryear = "";
        string _ncb = "";
        string _policystartdate = "";
        string _userfirstname = "";

        Int64 _cecarid = 0;

        if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
        {
            _cecarid = Convert.ToInt64(Session[General.CarId]);
            Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
            Int64 _userId = 0;

            if (Session[General.UserId] != null)
            {
                _userId = Convert.ToInt64(Session[General.UserId].ToString());
            }

            CE.User.Profile usrprofile = new Profile();
            ProfileDB usrprofiledb = new ProfileDB();

            usrprofile = usrprofiledb.GetProfile(_userId);
            if (usrprofile != null)
            {
                _userfirstname = usrprofile.FirstName;
            }

            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(_cecarid, _userId);

            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(_cecarid, _cepolicyid, _userId);

            if (_cardetail != null)
            {
                if (_cardetail.MakeModelDesc != null && _cardetail.MakeModelDesc != "")
                    _makemodel = _cardetail.MakeModelDesc;
                else
                    _makemodel = _cardetail.CarModelName + " " + _cardetail.Body + " " + _cardetail.CC + "cc " + _cardetail.Door.ToString() + " doors";
                _caryear = _cardetail.ManufactYear.ToString();

                _makemodel = _makemodel.Replace("_", " ");
            }

            if (_carpolicy != null)
            {
                if (_carpolicy.GarageType.ToString().Trim() == "1")
                    _garagetype = Resources.CarInsurance.Garage_Authorized;
                else
                    _garagetype = Resources.CarInsurance.Garage_Dealer;

                _ncb = _carpolicy.NCDPercent.ToString();
                _policystartdate = _carpolicy.CoverageCommenceDate.ToString("dd/MMM/yyyy");
            }
        }

        string _refno = "";
        string _companyName = "";
        string _insurerimageurl = "";
        string _package = "";
        string _annualprice = "";
        string _excess = "";
        string _promotionprice = "";

        bool _isDamageShowImage = false;
        string _damage = "0";
        bool _isFireShowImage = false;
        string _fire = "0";
        bool _isTheftShowImage = false;
        string _theft = "0";
        string _medicalexp = "";
        string _losspe = "";
        string _lossuse = "";
        string _padriver = "";
        string _tppd = "";
        string _bailbond = "";
        string _providercompanyid = "";
        bool _isFloodCovered = false;

        if (qs_carselected != "" && Session[General.UserId] != null && Session[General.CarId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);



                string CITempResultId = qs_carselected;

                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());

                            if (dtFiltered.Rows[iRows]["packagename"].ToString() != "GluayGluay.com Special")
                            {
                                if (Session["Language"] != null)
                                {
                                    if (Session["Language"].ToString() == "th-TH")
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "1");
                                    else
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }
                                else
                                {
                                    //english
                                    _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + CE.Global.General.GetProviderCompanyLogo(_providercompanyid); //"http://www.gluaygluay.com/"
                            }
                            else
                            {
                                _companyName = "";

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + "/images/public/logo/gluaygluay_logo.png";
                            }

                            _package = dtFiltered.Rows[iRows]["packagename"].ToString();


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"]) != Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"]))
                            {
                                _annualprice = "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())) + " " + Resources.CarInsurance.Baht + "</s>";
                            }

                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";

                            _annualprice = dtFiltered.Rows[iRows]["annualpremium"].ToString();
                            _promotionprice = _annualprice;
                            //_promotionprice = dtFiltered.Rows[iRows]["promotionprice"].ToString();

                            _excess = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));

                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()) == 0)
                            {
                                _isDamageShowImage = true;
                            }
                            else
                            {
                                _damage = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()));
                            }


                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()) == 0)
                                _isFireShowImage = true;
                            else
                                _fire = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()));

                            //Theft
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()) == 0)
                                _isTheftShowImage = true;
                            else
                                _theft = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()));

                            _tppd = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPPD"].ToString()));

                            _losspe = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIA"].ToString()));

                            _lossuse = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIP"].ToString()));

                            _padriver = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PADriver"].ToString()));

                            _medicalexp = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            _bailbond = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["BailBond"].ToString()));

                            if (dtFiltered.Rows[iRows]["IsFloodCover"].ToString() != "0")
                            {
                                _isFloodCovered = true;
                            }
                        }
                    }
                }
            }
            else if (Cache["CarResult" + Session[General.CarId].ToString()] != null)//13 Apr 2015 - Songkran's Promotion - Start
            {
                DataView dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);



                string CITempResultId = qs_carselected;

                dv.RowFilter = " CITempResultId in (" + CITempResultId + ")";
                DataTable dtFiltered = dv.ToTable();
                if (Cache["CarResult" + Session[General.CarId].ToString()] != null)
                {
                    if (dtFiltered.Rows.Count > 0)
                    {
                        int rowCount = dtFiltered.Rows.Count;

                        for (int iRows = 0; iRows < rowCount; iRows++)
                        {
                            _providercompanyid = dtFiltered.Rows[iRows]["ProviderCompanyId"].ToString();
                            _refno = General.GetReferenceNumber(_cecarid.ToString(), _providercompanyid, dtFiltered.Rows[iRows]["packagename"].ToString());

                            if (dtFiltered.Rows[iRows]["packagename"].ToString() != "GluayGluay.com Special")
                            {
                                if (Session["Language"] != null)
                                {
                                    if (Session["Language"].ToString() == "th-TH")
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "1");
                                    else
                                        _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }
                                else
                                {
                                    //english
                                    _companyName = General.GetProviderName(int.Parse(_providercompanyid), "2");
                                }

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + CE.Global.General.GetProviderCompanyLogo(_providercompanyid); //"http://www.gluaygluay.com/"
                            }
                            else
                            {
                                _companyName = "";

                                _insurerimageurl = System.Configuration.ConfigurationSettings.AppSettings["TH.MobileUrl"].ToString() + "/images/public/logo/gluaygluay_logo.png";
                            }

                            _package = dtFiltered.Rows[iRows]["packagename"].ToString();


                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"]) != Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"]))
                            {
                                _annualprice = "<s>" + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["annualpremium"].ToString())) + " " + Resources.CarInsurance.Baht + "</s>";
                            }

                            _annualprice = _annualprice + "<div style='color:#F00;font-size:20px;font-weight:bold;' >";
                            _annualprice = _annualprice + String.Format("{0:0,0.00}", Convert.ToSingle(dtFiltered.Rows[iRows]["promotionprice"].ToString())); //"999.00";
                            _annualprice = _annualprice + "</div>";

                            _annualprice = dtFiltered.Rows[iRows]["annualpremium"].ToString();
                            _promotionprice = _annualprice;
                            //_promotionprice = dtFiltered.Rows[iRows]["promotionprice"].ToString();

                            _excess = String.Format("{0:0,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["DEC"].ToString()));

                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()) == 0)
                            {
                                _isDamageShowImage = true;
                            }
                            else
                            {
                                _damage = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["SumInsured"].ToString()));
                            }


                            if (Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()) == 0)
                                _isFireShowImage = true;
                            else
                                _fire = String.Format("{0:#,0}", Convert.ToInt32(dtFiltered.Rows[iRows]["Fire"].ToString()));

                            //Theft
                            if (Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()) == 0)
                                _isTheftShowImage = true;
                            else
                                _theft = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["Theft"].ToString()));

                            _tppd = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPPD"].ToString()));

                            _losspe = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIA"].ToString()));

                            _lossuse = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["TPBIP"].ToString()));

                            _padriver = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["PADriver"].ToString()));

                            _medicalexp = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["MedicalExpense"].ToString()));

                            _bailbond = String.Format("{0:#,0}", Convert.ToSingle(dtFiltered.Rows[iRows]["BailBond"].ToString()));

                            if (dtFiltered.Rows[iRows]["IsFloodCover"].ToString() != "0")
                            {
                                _isFloodCovered = true;
                            }
                        }
                    }
                }
            } //13 Apr 2015 - Songkran's Promotion - End
        }
        string _emailList = "", _title = "";
        System.Text.StringBuilder _message = new System.Text.StringBuilder();
       _emailList = Session[CE.Global.General.UserEmail].ToString();        
        _title = "";

        _title = "<mobile> GluayGluay.com: " + Resources.EmailMessage.EmailThisTitle + " " + _userfirstname + " (Quotation number : " + _refno + ")";


        string _strCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("Mobile.IsCXLive");
        string _mailBody = "";
        string domainUrl = "";
        Uri myUri = new Uri(HttpContext.Current.Request.Url.ToString());
        domainUrl = "http://www.gluaygluay.com/mobile";
        if (_strCXLive == "0")
        {
            domainUrl = "http://test.gluaygluay.com.gluaygluay.info/mobile";
        }

        #region "Mail Body"

        #region Header
        _mailBody = "<html>";
        _mailBody += "<head>";
        _mailBody += "<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />";
        _mailBody += "<title>GluayGluay</title>";
        _mailBody += "<style>";

        _mailBody += ".body {";
        _mailBody += "margin-left: 0px;";
        _mailBody += "margin-top: 0px;";
        _mailBody += "margin-right: 0px;";
        _mailBody += "margin-bottom: 0px;";
        _mailBody += "font-family: Arial, sans-serif;";
        _mailBody += "font-size: 14px;";
        _mailBody += "color: #000000;";
        _mailBody += "background-repeat: repeat-x;";
        _mailBody += "background-color: #fff;";
        _mailBody += "text-decoration: none;}";

        _mailBody += "</style>";
        _mailBody += "</head>";
        #endregion

        _mailBody += "<body class='body'>";
        _mailBody += "<table width='800' border='0' align='center' cellpadding='0' cellspacing='0' style='line-height:20px;font-size:14px;'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='1474' valign='top'>";
        _mailBody += "<table width='800' height='100' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td><span class='email-banner'><img src='" + domainUrl + "/images/email-header.jpg' width='800' height='100' alt='' /></span></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        #region Thank you
        _mailBody += "<table width='329' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='329'><strong>" + Resources.EmailMessage.EmailThisHeader + "</strong></td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += " <td>" + Resources.Proposal.ThankYou + "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        #region Car Details
        _mailBody += "<table width='700' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td valign='top' bgcolor='#C1C1C1'>";
        _mailBody += "<br />";
        _mailBody += "<table width='800' border='0' cellspacing='1' cellpadding='1'>";
        //_mailBody += "<tr>";
        //_mailBody += "<td height='26' colspan='4' bgcolor='#E7E7E7'>";
        //_mailBody += "<span style='font-size: 14px; font-weight: bold; padding-left: 10px; padding-bottom: 5px;";
        //_mailBody += "padding-top: 5px;'>" + Resources.Proposal.OrderNo + " " + _refNo + "</span>";
        //_mailBody += "</td>";
        //_mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td width='150' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.CarYear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='363' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _caryear + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='148' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.NCB + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='126' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _ncb + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.MakeModel + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='30' colspan='3' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _makemodel + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.GarageType + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td colspan='3' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _garagetype + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion


        bool IsGGSpecial = false;
        //logo
        string logourl = "";
        string package = _package;
        if (_package != "GluayGluay.com Special")
        {
            logourl = domainUrl + CE.Global.General.GetProviderCompanyLogo(_providercompanyid);
        }
        else
        {
            //[Yui] @13/09/2013
            IsGGSpecial = true;
            // --- End ---

            logourl = domainUrl + "/images/gg-logo/gluaygluay-logo.png";
            package += " (" + Resources.CarInsuranceResultPage.SpecialNCB + ")";
        }

        #region Main body

        #region Not Using
        float _fMonthlyPremiumAmount = Convert.ToSingle(_annualprice) / 4;
        string monthlyInstallment = "";

        if (_fMonthlyPremiumAmount > 0.0f)
        {
            string _monthlyPremiumAmount = String.Format("{0:0,0.00}", _fMonthlyPremiumAmount);
            monthlyInstallment = _monthlyPremiumAmount + "/mth<br/>";
        }
        else
        {
            monthlyInstallment = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        #endregion

        _mailBody += "<table width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='129' valign='top'>";
        _mailBody += "<table width='520' border='0' cellspacing='1' cellpadding='1' bgcolor='#C1C1C1'>";

        #region Provider Logo & Package name
        _mailBody += "<tr>";
        _mailBody += "<td height='25' colspan='2' bgcolor='#FFFFFF' align='center'>";
        _mailBody += "<span style='padding: 10px;'>";
        _mailBody += "<img src='" + logourl + "' alt='' /></span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "<tr>";
        _mailBody += "<td width='324' height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.ProposalForm.Package + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td width='193' height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += package + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Deductible
        float _fDEC = 0.0f;//Convert.ToSingle(_excess.Replace(",",""));
        if (!float.TryParse(_excess.Replace(",", ""), out _fDEC))
        {
            _fDEC = 0.0f;
        }
        string deductible = "";
        if (_fDEC > 0.0f)
        {
            deductible = String.Format("{0:0,0.00}", _fDEC);
        }
        else
        {
            deductible = Resources.CarInsuranceResultPage.Waived;
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.DEC + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += deductible + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Own Damage
        string suminsured = "0";// String.Format("{0:#,0}", Convert.ToSingle(_damage.Replace(",", "")));
        float _flsuminsured = 0.0f;
        if (!float.TryParse(_damage.Replace(",", ""), out _flsuminsured))
        {
            _flsuminsured = 0.0f;
        }
        suminsured = String.Format("{0:#,0}", _flsuminsured);
        if (_flsuminsured == 0)
        {
            suminsured = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.OwnDamage + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += suminsured + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Fire
        string fire = "0";// String.Format("{0:#,0}", Convert.ToSingle(_fire.Replace(",", "")));
        float _flfire = 0.0f;
        if (!float.TryParse(_fire.Replace(",", ""), out _flfire))
        {
            _flfire = 0.0f;
        }
        fire = String.Format("{0:#,0}", _flfire);
        if (_flfire == 0)
        {
            fire = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.Fire + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += fire + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Theft
        string theft = "0";// String.Format("{0:#,0}", Convert.ToSingle(_theft.Replace(",", "")));
        float _fltheft = 0.0f;
        if (!float.TryParse(_theft.Replace(",", ""), out _fltheft))
        {
            _fltheft = 0.0f;
        }
        theft = String.Format("{0:#,0}", _fltheft);
        if (_fltheft == 0)
        {
            theft = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.Theft + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += theft + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPPD
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPPD + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _tppd + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPBIA
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPBIA + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _losspe + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region TPBIP
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TPBIP + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _lossuse + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region PA Driver
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.PADriver + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _padriver + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Medical Expense
        int _MedicalExpense = 0;// Convert.ToInt32(_medicalexp.Replace(",", ""));
        if (int.TryParse(_medicalexp.Replace(",", ""), out _MedicalExpense))
        {
            _MedicalExpense = 0;
        }
        string medicalExpense = "";
        if (_MedicalExpense == 0)
        {
            medicalExpense = "<img src='" + domainUrl + "/images/icons/error.png' width='16' alt='NA' />";
        }
        else
        {
            medicalExpense = String.Format("{0:#,0}", Convert.ToSingle(_MedicalExpense.ToString()));
        }
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.MED + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += medicalExpense + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Bail Bond
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.BailBond + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#E7E7E7' style='text-align:right;'>";
        _mailBody += "<span style='font-size: 14px; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += _bailbond + "</span>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        #region Premium (+taxes & duties)
        _mailBody += "<tr>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF'>";
        _mailBody += "<span style='font-size: 14px; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += Resources.Proposal.TotalVMI + "</span>";
        _mailBody += "</td>";
        _mailBody += "<td height='25' bgcolor='#FFFFFF' style='text-align:right;'>";

        //Sakthi on 10 Nov 2014 - Start
        if (Convert.ToSingle(_annualprice) != Convert.ToSingle(_promotionprice))
        {
            _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
            _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_annualprice)) + " " + Resources.CarInsurance.Baht + "</span><br />";
        }
        _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-right: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_promotionprice)) + " " + Resources.CarInsurance.Baht + "</span>";
        //if (_isCTPL == "No")
        //{
        //    if (Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString()) != Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"]))
        //    {
        //        _mailBody += "<span style='font-size: 16px; text-decoration: line-through; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //        _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["annualpremium"].ToString())) + "</span><br />";
        //    }
        //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(dtResults.Rows[0]["PromotionPrice"].ToString())) + "</span>";
        //}
        //else
        //{
        //    _mailBody += "<span style='font-size: 20px; color: #3A5999; padding-left: 10px; padding-bottom: 5px; padding-top: 5px;'>";
        //    _mailBody += String.Format("{0:0,0.00}", Convert.ToSingle(_Premium)) + "</span>";
        //}
        //Sakthi on 10 Nov 2014 - End
        _mailBody += "</td>";
        _mailBody += "</tr>";
        #endregion

        _mailBody += "</table>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";
        #endregion

        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='787' height='26' colspan='4' bgcolor='#FFFFFF'>";

        #region Remarks
        _mailBody += "<a href='tel:022688222'><img src='" + domainUrl + Resources.EmailMessage.HotlineBanner + "' alt='Call Us at 02 268 8222' width='270' border='0' /></a>";
        _mailBody += "<br /><br /><br />";

        //_message.Append("<strong>Remarks</strong><br />");
        _mailBody += "<strong>" + Resources.ProposalForm.Remarks + "</strong><br />";
        //_message.Append("1 - The quotation valid for 7 days and subject to change without notice according to policy of company<br />");
        _mailBody += Resources.ProposalForm.RemarkOne + "<br />";
        //_message.Append("2- Premium and coverage are subject to underwriting criteria of insurance company.<br />");
        _mailBody += Resources.ProposalForm.RemarkTwo + "<br />";

        _mailBody += "<hr />";

        _mailBody += Resources.ProposalForm.ThisQuoteis + "<br />";
        //_mailBody += "<i>" + Resources.ProposalForm.EmailDisclaimer + "</i>";
        //_mailBody += "This Quote is subject to the insurer's final confirmation and coverage is only effective";
        //_mailBody += "when the";
        //_mailBody += "<br />";
        //_mailBody += "insurer has accepted the risk.";
        #endregion

        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<hr />";

        #region Footer

        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td colspan='2' valign='top'>";
        _mailBody += "<strong>" + Resources.WelcomeEmail.CompanyAdd1 + "</strong><br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd2 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd3 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyAdd4 + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyPhone + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyFax + "<br />";
        _mailBody += Resources.WelcomeEmail.CompanyEmail + "<br />";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "<br />";

        _mailBody += "<table width='300' border='0' align='center' cellpadding='0' cellspacing='0'>";
        _mailBody += "<tr>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://www.facebook.com/GGmotor' target='_blank'><img src='" + domainUrl + "/images/icons/fb-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='https://plus.google.com/+Gluaygluay/posts' target='_blank'><img src='" + domainUrl + "/images/icons/g-plus-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://www.youtube.com/channel/UCZ4gMtlXymBHxvcXO2cR1vA' target='_blank'><img src='" + domainUrl + "/images/icons/youtube-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='44' style='text-align: center'>";
        _mailBody += "<a href='http://iconosquare.com/ggmotor' target='_blank'><img src='" + domainUrl + "/images/icons/instagram-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "<td width='43' style='text-align: center'>";
        _mailBody += "<a href='http://www.linkedin.com/company/-com-gluaygluay-com-' target='_blank'><img src='" + domainUrl + "/images/icons/linkedin-big.png' width='44' height='42'></a>";
        _mailBody += "</td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";

        _mailBody += "<hr />";
        _mailBody += "<table style='line-height: 20px;' width='800' border='0' cellspacing='0' cellpadding='0' background='" + domainUrl + "/images/email-footer.jpg'>";
        _mailBody += "<tr>";
        _mailBody += "<td height='49'><br><p style='text-align: center'>© 2015 gluaygluay.com. All rights reserved.<br>";
        _mailBody += Resources.EmailMessage.AutoEmail + "</p></td>";
        _mailBody += "</tr>";
        _mailBody += "</table></td>";
        _mailBody += "</tr>";
        _mailBody += "</table>";
        _mailBody += "</body>";
        _mailBody += "</html>";
        #endregion

        #endregion

        if (MyMailManager.SendNotification(_emailList, _title, _mailBody))
        {
            Response.Redirect("promo-email-confirm.aspx?type=email&resultid=" + carresultid + "&qid=" + hdnQuoteId.Value + "&cid=" + hdnCarId.Value + "&pid=" + hdnPolicyId.Value + "&sent=1");
        }

    }

    public void PromotionIdUpdate(Int64 UserId, Int64 CarId)
    {
        if (UserId > 0)
        {
            Int64 _result = -1;
            MyDatabase _db = new MyDatabase("Mobile.CX_DBConnectionString");
            string _spName = "sprocCarDetailTHInsertUpdateSingleItemPromotion";
            DataSet _dsAmount = new DataSet();
            SortedList _paraList = new SortedList();
            _paraList.Add("@CarId", CarId);
            _paraList.Add("@PromoType", 3);
            _result = _db.ExecuteSP(_spName, _paraList);
        }
    }

}
